<template>
  <el-drawer v-model="drawer" :direction="direction" @close="closeclick">
    <template #title>
      <h4>{{ title }}</h4>
    </template>
    <template #default>
      <el-form
        ref="ruleFormRef"
        :model="tableData"
        status-icon
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item
          label="用户名称"
          prop="userName"
          :rules="[
            {
              required: true,
              message: '用户名称不能为空',
              trigger: 'blur'
            }
          ]"
        >
          <el-input
            v-model="tableData.userName"
            :clearable="true"
            placeholder="请输入用户名称"
          />
        </el-form-item>

        <el-form-item
          label="用户账户"
          prop="userAccount"
          :rules="[
            {
              required: true,
              message: '用户账户不能为空',
              trigger: 'blur'
            }
          ]"
        >
          <el-input
            v-model="tableData.userAccount"
            :clearable="true"
            placeholder="请输入用户账户"
          />
        </el-form-item>
        <el-form-item
          label="用户密码"
          prop="userPassword"
          :rules="[
            {
              required: true,
              message: '用户密码不能为空',
              trigger: 'blur'
            }
          ]"
        >
          <el-input
            v-model="tableData.userPassword"
            :clearable="true"
            placeholder="请输入用户密码"
          />
        </el-form-item>
        <el-form-item
          label="用户角色"
          prop="roleId"
          :rules="[
            {
              required: true,
              message: '用户角色不能为空',
              trigger: ['blur', 'change']
            }
          ]"
        >
          <el-select
            v-model="tableData.roleId"
            clearable
            :multiple="true"
            placeholder="请选择用户名称"
            @visible-change="userRoleChange"
            @change="usechange"
          >
            <el-option
              v-for="item in user"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="设备名称"
          prop="deviceId"
          :rules="[
            {
              required: true,
              message: '设备名称不能为空',
              trigger: 'blur'
            }
          ]"
        >
          <el-select
            v-model="tableData.deviceId"
            clearable
            :multiple="true"
            placeholder="请选择设备名称"
            @visible-change="obtainDeviceId"
          >
            <el-option
              v-for="item in deviceData"
              :key="item.deviceId"
              :label="item.deviceName"
              :value="item.deviceId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="最后更新时间">
          <div>{{ tableData.lastUpdateTime }}</div>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :loading="loadinga"
            @click="submitForm(tableData)"
            >提交</el-button
          >
          <el-button @click="resetForm">取消</el-button>
        </el-form-item>
      </el-form>
    </template>
  </el-drawer>
</template>

<script  setup>
import { ref, defineProps, watch, defineEmits, reactive } from 'vue'
import { configuration } from '@/api/equipment'
import { accountSaveupdate, roleInfo } from '@/api/user'
import { ElMessage } from 'element-plus'
const ruleFormRef = ref()
const loadinga = ref(false)

const props = defineProps({
  showDrawer: {
    type: Boolean,
    required: true
  },
  userInfoData: {
    type: Object
  },
  title: {
    type: String
  }
})
const drawer = ref(false)
const emit = defineEmits(['clickShow'])
watch(
  () => props.showDrawer,
  (val) => {
    drawer.value = val
  }
)

// 父级传递来的数据
const tableData = reactive({})
// const userRole = ref([])
watch(
  () => props.userInfoData,
  (val) => {
    Object.assign(tableData, val)
    // 绑定新的验证规则 值只有 数字 userArr:[1,2,3,4]的形式
    const userArr = { roleId: [] }
    // 合并对象 这样不会丢失响应式
    Object.assign(val, userArr)
    // 这里是处理设备的因为要传递多个id
    const deviceArr = { deviceId: [] }
    Object.assign(val, deviceArr)
    if (val.userRole instanceof Array && val.device instanceof Array) {
      val.roleId = val.userRole.map((item) => {
        return item.roleId
      })
      val.deviceId = val.device.map((item) => {
        return item.deviceId
      })
      // console.log(val)
    }
    if (val.userId === '' || val.userId === null) {
      ruleFormRef.value.resetFields()
      Object.keys(tableData).forEach((key) => {
        tableData[key] = ''
      })
    }
  },
  {
    // 立即执行
    immediate: true,
    // 深度监听
    deep: true
  }
)

const usechange = (val) => {
  console.log(val)
}
// console.log(tableData)
// 用户角色接口
const user = ref([])
const getuserRole = () => {
  roleInfo().then((res) => {
    user.value = res.data
  })
}
const userRoleChange = (val) => {
  if (val) {
    getuserRole()
  }
}
// 调用设备接口
const getdevice = () => {
  configuration().then((res) => {
    console.log(res)
    deviceData.value = res.data.map((item) => {
      const obj = {}
      obj.deviceId = item.deviceId
      obj.deviceName = item.deviceName
      return obj
    })
  })
}
getdevice()
const deviceData = ref([])
const obtainDeviceId = (val) => {
  if (val) {
    getdevice()
  }
}
// 提交
const submitForm = (tableData) => {
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      loadinga.value = true
      setTimeout(() => {
        loadinga.value = false
        const { device, userRole, lastUpdateTime, loading, ...obj } = tableData
        console.log(obj)
        accountSaveupdate(obj)
          .then((res) => {
            ElMessage({
              message: res.message,
              type: 'success'
            })
            emit('clickShow', false, res.code)
          })
          .catch((err) => {
            ElMessage.error(err.message)
            emit('clickShow', false)
          })
      }, 500)
    } else {
      ElMessage.error('失败')
      return false
    }
  })
}
// 取消
const resetForm = () => {
  ruleFormRef.value.resetFields()
  emit('clickShow', false)
}

// 监听抽屉关闭
const closeclick = () => {
  ruleFormRef.value.resetFields()
  emit('clickShow', false)
  Object.keys(tableData).forEach((key) => {
    tableData[key] = ''
  })
}
</script>
<style lang="scss" scoped>
::v-deep .el-input {
  width: 265px;
}
</style>
